package org.agile4j.rpc.common.codec;

import org.agile4j.rpc.common.utils.SerializtionUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 提供 RPC 编码
 * 扩展 Netty 的MessageToByteEncoder抽象类的encode方法
 * 
 * @author Administrator
 */
public class RpcEncoder extends MessageToByteEncoder{
	
	private Class<?> genericClass ;

	public RpcEncoder(Class<?> genericClass) {
		this.genericClass = genericClass ;
	}

	@Override
	public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {
		if (genericClass.isInstance(in)) {	// 自身类.class.isInstance(自身实例或子类实例)  返回true
			byte[] data = SerializtionUtil.serialize(in) ;
			out.writeInt(data.length) ;
			out.writeBytes(data) ;
		}
	}

}
